<template>
  <div class="chart-query-page">
    <div class="chat-container">
      <!-- 聊天内容区域 -->
      <div class="chat-content" ref="chatContentRef">
        <!-- 翻译加载动画 -->
        <div v-if="isTranslating && !isSplitScreen" class="translation-loading">
          <div class="loading-container">
            <div class="loading-avatar">
              <img src="@/assets/十一建logo/1.gif" alt="翻译助手" class="avatar-gif" />
            </div>
            <div class="loading-content">
              <div class="loading-header">
                <div class="loading-title">
                  <span class="loading-icon">🔄</span>
                  <h3>正在翻译中...</h3>
                </div>
                <div class="loading-progress">
                  <div class="progress-bar">
                    <div class="progress-fill" :style="{ width: loadingProgress + '%' }"></div>
                  </div>
                  <span class="progress-text">{{ loadingProgress }}%</span>
                </div>
              </div>
              <div class="loading-steps">
                <div class="step" :class="{ active: currentStep >= 1, completed: currentStep > 1 }">
                  <div class="step-icon">
                    <el-icon v-if="currentStep > 1"><Check /></el-icon>
                    <div v-else-if="currentStep === 1" class="step-spinner"></div>
                    <span v-else>1</span>
                  </div>
                  <span class="step-text">文本分析</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 2, completed: currentStep > 2 }">
                  <div class="step-icon">
                    <el-icon v-if="currentStep > 2"><Check /></el-icon>
                    <div v-else-if="currentStep === 2" class="step-spinner"></div>
                    <span v-else>2</span>
                  </div>
                  <span class="step-text">语言识别</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 3, completed: currentStep > 3 }">
                  <div class="step-icon">
                    <el-icon v-if="currentStep > 3"><Check /></el-icon>
                    <div v-else-if="currentStep === 3" class="step-spinner"></div>
                    <span v-else>3</span>
                  </div>
                  <span class="step-text">智能翻译</span>
                </div>
                <div class="step" :class="{ active: currentStep >= 4, completed: currentStep > 4 }">
                  <div class="step-icon">
                    <el-icon v-if="currentStep > 4"><Check /></el-icon>
                    <div v-else-if="currentStep === 4" class="step-spinner"></div>
                    <span v-else>4</span>
                  </div>
                  <span class="step-text">结果优化</span>
                </div>
              </div>
              <div class="loading-tips">
                <p class="tip-text">{{ currentTip }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 分屏显示区域 -->
        <div v-if="isSplitScreen" class="split-screen-container">
          <div class="split-screen-top">
            <div class="left-avatar">
              <img src="@/assets/十一建logo/1.gif" alt="用户动图" class="top-avatar-gif" />
            </div>
            <div class="right-close">
              <button class="close-split-btn" @click="closeSplitScreen" title="关闭分屏">
                <el-icon><Close /></el-icon>
              </button>
            </div>
          </div>
          <div class="split-screen-content">
            <div class="split-panel original-panel">
              <div class="panel-header">
                <el-icon class="status-icon input-status"><CircleCheck /></el-icon>
                <h4>原文</h4>
              </div>
              <div class="panel-content">
                <div 
                  class="panel-text markdown-content" 
                  v-html="renderedOriginalMarkdown"
                ></div>
              </div>
              <div class="panel-actions">
                <button class="panel-action-btn" @click="copyPanelText(splitScreenData.original)" title="复制原文">
                  <el-icon><DocumentCopy /></el-icon>
                </button>
                <button class="panel-action-btn" @click="downloadText(splitScreenData.original, '原文.txt')" title="下载原文">
                  <el-icon><Download /></el-icon>
                </button>
              </div>
            </div>
            <div class="split-panel translated-panel">
              <div class="panel-header">
                <el-icon class="status-icon complete-status"><SuccessFilled /></el-icon>
                <h4>译文</h4>
              </div>
              <div class="panel-content">
                <div 
                  class="panel-text markdown-content" 
                  v-html="renderedMarkdown"
                ></div>
              </div>
              <div class="panel-actions">
                <button class="panel-action-btn" @click="retranslate" title="重新翻译" :disabled="isTranslating">
                  <el-icon><Refresh /></el-icon>
                </button>
                <button class="panel-action-btn" @click="copyPanelText(splitScreenData.translated)" title="复制译文">
                  <el-icon><DocumentCopy /></el-icon>
                </button>
                <button class="panel-action-btn" @click="downloadText(splitScreenData.translated, '译文.txt')" title="下载译文">
                  <el-icon><Download /></el-icon>
                </button>
              </div>
            </div>
          </div>
        </div>

        <div v-if="!isSplitScreen && !isTranslating" class="chat-welcome">
          <div class="welcome-avatar">
            <img src="@/assets/十一建logo/1.gif" alt="智能助手" class="avatar-gif" />
          </div>
          <div class="welcome-text">
            <h3>Hello,张三</h3>
            <p>我是您的全能翻译助手，支持文本、文档、图片多格式内容互译,</p>
              <p>实时提供地道、专业、场景化译文</p>
           
          </div>
        </div>
        
        <!-- 打字指示器 -->
        <div v-if="isTyping" class="message assistant">
          <div class="message-avatar">
            <img src="@/assets/十一建logo/1.gif" alt="AI助手" class="avatar-gif" />
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-container">
          <div class="input-wrapper"
               @drop="handleDrop"
               @dragover="handleDragOver"
               @dragenter="handleDragEnter"
               @dragleave="handleDragLeave"
               :class="{ 'drag-over': isDragOver }"
               style="position: relative;">
            <!-- 已上传文件列表 - 显示在输入框上方 -->
            <div v-if="uploadedFiles.length > 0" class="uploaded-files-outside">
              <div v-for="file in uploadedFiles" :key="file.id" class="file-tab">
                <div class="file-tab-icon">
                  <svg viewBox="0 0 24 24" width="16" height="16" fill="#4285f4">
                    <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/>
                  </svg>
                </div>
                <div class="file-tab-content">
                  <div class="file-tab-title">{{ getFileDisplayName(file.name) }}</div>
                  <div class="file-tab-url">{{ file.name }}</div>
                </div>
                <button class="file-tab-close" @click="removeFile(file.id)" title="移除文件">
                  <svg viewBox="0 0 24 24" width="12" height="12">
                    <path d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" fill="currentColor"/>
                  </svg>
                </button>
              </div>
            </div>
            
            <!-- 文本输入区域 -->
            <div class="textarea-container">
              <textarea
                v-model="inputMessage"
                placeholder="您可以输入需要翻译的文本内容"
                @keyup.enter="handleEnterKey"
                @paste="handlePaste"
                @input="adjustTextareaHeight"
                ref="textareaRef"
                class="message-input"
                rows="1"
              />
            </div>
            
            <!-- 底部功能区 -->
            <div class="input-bottom">
              <div class="input-controls">
                <el-select
                  v-model="selectedLanguage"
                  size="small"
                  class="language-select"
                  style="width: 120px;"
                  placeholder="选择语种"
                >
                  <el-option
                    v-for="lang in languageOptions"
                    :key="lang.value"
                    :label="lang.label"
                    :value="lang.value"
                  />
                </el-select>
                <el-select
                  v-model="selectedModel"
                  size="small"
                  class="model-select"
                  style="width: 120px; margin-left: 8px;"
                  popper-class="model-select-popper"
                >
                  <el-option
                    v-for="model in modelOptions"
                    :key="model.value"
                    :label="model.label"
                    :value="model.value"
                  />
                </el-select>
              </div>
              
              <!-- 右侧按钮组 -->
              <div class="input-actions">
                <!-- 上传文件按钮 -->
                <el-button
                  class="upload-btn"
                  @click="triggerFileUpload"
                  style="width: 36px; height: 36px; border-radius: 8px; padding: 0; display: flex; align-items: center; justify-content: center;"
                  title="上传文件"
                >
                  <img src="@/assets/icon/file.svg" alt="上传文件" style="width: 36px; height: 36px;" />
                </el-button>
                <!-- 发送按钮 -->
                <el-button
                  class="send-btn"
                  type="primary"
                  style="width: 36px; height: 36px; border-radius: 8px; padding: 0; display: flex; align-items: center; justify-content: center;"
                  @click="isTranslating ? stopTranslation() : sendMessage()"
                  :disabled="!inputMessage.trim() && uploadedFiles.length === 0 && !isTranslating"
                  :title="isTranslating ? '停止翻译' : '发送'"
                >
                  <el-icon v-if="isTranslating" :size="24">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                      <path d="M6,6H18V18H6V6Z" fill="currentColor"/>
                    </svg>
                  </el-icon>
                  <el-icon v-else :size="24"><Promotion /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 隐藏的文件输入 -->
        <input
          ref="fileInputRef"
          type="file"
          multiple
          accept=".txt,.doc,.docx,.pdf,.jpg,.jpeg,.png,.gif"
          @change="handleFileUpload"
          style="display: none;"
        />

        <!-- 底部提示 -->
        <div class="input-footer">
          <span class="footer-text">以上内容由大模型生成,请您注意甄别,并自行判断其准确性和适用性.</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, watch, computed } from 'vue'
import { ElIcon, ElButton, ElSelect, ElOption, ElMessage } from 'element-plus'
import { Promotion, Close, CircleCheck, SuccessFilled, DocumentCopy, Download, Check, Refresh } from '@element-plus/icons-vue'
import MinimalButton from '@/components/minimal-ui/Button.vue'
import { translateText, uploadFile, mockTranslateText, mockUploadFile, languageMapping, type TranslationRequest } from '@/api/translation'
import { marked } from 'marked'

const username = 'Admin'
const inputMessage = ref('')
const isTyping = ref(false)
const chatContentRef = ref<HTMLElement>()
const activeTab = ref('enterprise')
const selectedKnowledge = ref<string[]>([])
const fileInputRef = ref<HTMLInputElement>()
const uploadedFiles = ref<UploadedFile[]>([])
const messages = ref<Message[]>([])
const selectedLanguage = ref('zh')
const selectedModel=ref('deepseek')
const currentTypingTimeout = ref<number | null>(null)

// 翻译相关状态
const isTranslating = ref(false)
const loadingProgress = ref(0)
const currentStep = ref(0)
const currentTip = ref('')

// 分屏相关状态
const isSplitScreen = ref(false)
const splitScreenData = ref<{
  original: string
  translated: string
}>({
  original: '',
  translated: ''
})

// Markdown 渲染计算属性
const renderedMarkdown = computed(() => {
  if (!splitScreenData.value.translated) {
    return ''
  }
  try {
    return marked(splitScreenData.value.translated, {
      breaks: true,
      gfm: true
    })
  } catch (error) {
    console.error('Markdown 渲染错误:', error)
    return splitScreenData.value.translated
  }
})

// 原文 Markdown 渲染计算属性
const renderedOriginalMarkdown = computed(() => {
  if (!splitScreenData.value.original) {
    return ''
  }
  try {
    return marked(splitScreenData.value.original, {
      breaks: true,
      gfm: true
    })
  } catch (error) {
    console.error('原文 Markdown 渲染错误:', error)
    return splitScreenData.value.original
  }
})

// 翻译提示文案
const translationTips = [
  '正在分析文本结构...',
  '识别源语言类型...',
  '调用AI翻译引擎...',
  '优化翻译结果...',
  '翻译完成！'
]


const languageOptions = [
  { value: 'zh', label: '中文' },
  { value: 'en', label: '英语' },
  { value: 'ja', label: '日语' },
  { value: 'ko', label: '韩语' },
  { value: 'fr', label: '法语' },
  { value: 'de', label: '德语' },
  { value: 'es', label: '西班牙语' },
  { value: 'ru', label: '俄语' },
  { value: 'it', label: '意大利语' },
  { value: 'pt', label: '葡萄牙语' },
  { value: 'ar', label: '阿拉伯语' },
  { value: 'th', label: '泰语' },
  { value: 'vi', label: '越南语' }
]

const modelOptions = [
  { value: 'gpt-3.5', label: 'GPT-3.5（OpenAI）' },
  { value: 'gpt-4', label: 'GPT-4（OpenAI）' },
  { value: 'wenxin', label: '文心一言（百度）' },
  { value: 'qwen', label: '通义千问（阿里）' },
  { value: 'deepseek', label: 'DeepSeek' },
  { value: 'custom', label: '自定义模型' }
]

const enterpriseOptions = ref<KnowledgeOption[]>([
  { id: 'enterprise-a', name: '企业知识库分类A' },
  { id: 'enterprise-b', name: '企业知识库分类B' },
  { id: 'enterprise-c', name: '企业知识库分类C' },
  { id: 'enterprise-d', name: '企业知识库分类D' }
])

const personalOptions = ref<KnowledgeOption[]>([
  { id: 'personal-a', name: '个人知识库分类A' },
  { id: 'personal-b', name: '个人知识库分类B' },
  { id: 'personal-c', name: '个人知识库分类C' }
])

interface Message {
  type: 'user' | 'assistant'
  content: string
  time: string
  files?: UploadedFile[]
}

interface KnowledgeOption {
  id: string
  name: string
}

interface UploadedFile {
  id: string
  name: string
  size: number
  type: string
  file: File
}

function triggerFileUpload() {
  fileInputRef.value?.click()
}

function handleFileUpload(event: Event) {
  const target = event.target as HTMLInputElement
  const files = target.files
  
  if (files) {
    Array.from(files).forEach(file => {
      addFileToUpload(file)
    })
  }
  
  // 清空文件输入框
  if (target) {
    target.value = ''
  }
}

function removeFile(fileId: string) {
  const index = uploadedFiles.value.findIndex(file => file.id === fileId)
  if (index > -1) {
    uploadedFiles.value.splice(index, 1)
  }
}

function isImageFile(file: UploadedFile): boolean {
  return file.type.startsWith('image/')
}

function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

function getFileDisplayName(fileName: string): string {
  // 如果文件名太长，截取前面部分并添加省略号
  if (fileName.length > 20) {
    const extension = fileName.split('.').pop()
    const nameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'))
    return nameWithoutExt.substring(0, 15) + '...' + (extension ? '.' + extension : '')
  }
  return fileName
}

function getCurrentTime() {
  return new Date().toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

function scrollToBottom() {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
  })
}

function askQuestion(question: string) {
  inputMessage.value = question
  sendMessage()
}

// 处理回车键事件
function handleEnterKey(event: KeyboardEvent) {
  // 如果正在翻译，阻止回车发送
  if (isTranslating.value) {
    event.preventDefault()
    return
  }
  
  // 正常发送逻辑
  sendMessage()
}

function sendMessage() {
  if ((!inputMessage.value.trim() && uploadedFiles.value.length === 0) || isTranslating.value) return

  // 开始翻译流程
  startTranslation()
}

// 停止翻译功能
function stopTranslation() {
  if (isTranslating.value) {
    isTranslating.value = false
    loadingProgress.value = 0
    currentStep.value = 0
    ElMessage.info('翻译已停止')
  }
}

// 开始翻译流程
async function startTranslation() {
  const originalText = inputMessage.value.trim()
  const files = [...uploadedFiles.value]
  
  if (!originalText && files.length === 0) return

  // 重置所有状态 - 确保再次翻译时重新显示加载动画
  isSplitScreen.value = false
  isTranslating.value = false

  // 保存原文
  splitScreenData.value.original = originalText
  splitScreenData.value.translated = '' // 清空之前的译文

  // 清空输入
  inputMessage.value = ''
  uploadedFiles.value = []

  // 延迟一下再开始加载动画，确保UI更新
  setTimeout(() => {
    // 开始加载动画
    isTranslating.value = true
    loadingProgress.value = 0
    currentStep.value = 0
    currentTip.value = translationTips[0]

    // 调用真实翻译API
    performRealTranslation(originalText, files)
  }, 100)
}

// 执行真实翻译
async function performRealTranslation(originalText: string, files: UploadedFile[]) {
  try {
    let fileUrl = ''
    
    // 第一步：如果有文件，先上传文件
    if (files.length > 0) {
      currentStep.value = 1
      currentTip.value = '正在上传文件...'
      loadingProgress.value = 10
      
      const file = files[0] // 只处理第一个文件
      
      // 使用模拟上传（实际环境中使用 uploadFile）
      const uploadResult:any = await uploadFile(file.file,'')
    
        fileUrl = uploadResult?.file_url
        ElMessage.success(`文件上传成功!`)
      
    }
    
    // 第二步：准备翻译参数
    currentStep.value = 2
    currentTip.value = '准备翻译参数...'
    loadingProgress.value = 30
    
    const targetLanguage = languageMapping[selectedLanguage.value] || '中文'
    
    const translationParams: TranslationRequest = {
      url: fileUrl,
      user_input: originalText,
      target_language: targetLanguage
    }
    
    // 第三步：调用翻译API
    currentStep.value = 3
    currentTip.value = '正在翻译...'
    loadingProgress.value = 60
    
    // 使用模拟翻译API（实际环境中使用 translateText）
    const translationResult:any = await translateText(translationParams)
    
    // 第四步：处理翻译结果
    currentStep.value = 4
    currentTip.value = '处理翻译结果...'
    loadingProgress.value = 90
    if (files.length > 0) {
      splitScreenData.value.original = translationResult?.file_content
      splitScreenData.value.translated = translationResult?.target_result
    } else {
      splitScreenData.value.translated = translationResult?.target_result
    }
      
      // 第五步：完成
      currentStep.value = 5
      currentTip.value = translationTips[4]
      loadingProgress.value = 100
      
      // 延迟显示分屏结果
      setTimeout(() => {
        isTranslating.value = false
        isSplitScreen.value = true
        ElMessage.success('翻译完成！')
      }, 500)
  } catch (error) {
    console.error('翻译过程出错:', error)
    isTranslating.value = false
    isSplitScreen.value = false
    
    const errorMessage = error instanceof Error ? error.message : '翻译失败，请重试'
    ElMessage.error(errorMessage)
    
    // 恢复输入内容
    inputMessage.value = originalText
    uploadedFiles.value = files
  }
}

// 获取目标语言的显示名称
function getTargetLanguageDisplay(): string {
  return languageMapping[selectedLanguage.value] || '中文'
}

// 重新翻译功能
async function retranslate() {
  if (!splitScreenData.value.original && uploadedFiles.value.length === 0) {
    ElMessage.warning('没有可重新翻译的内容')
    return
  }
  
  // 恢复原始内容到输入框
  inputMessage.value = splitScreenData.value.original
  
  // 清空分屏数据
  isSplitScreen.value = false
  splitScreenData.value.translated = ''
  
  // 重新开始翻译
  await startTranslation()
}

function toggleKnowledge(id: string) {
  const index = selectedKnowledge.value.indexOf(id)
  if (index > -1) {
    selectedKnowledge.value.splice(index, 1)
  } else {
    selectedKnowledge.value.push(id)
  }
}

function removeKnowledge(id: string) {
  const index = selectedKnowledge.value.indexOf(id)
  if (index > -1) {
    selectedKnowledge.value.splice(index, 1)
  }
}

function getKnowledgeName(id: string) {
  const allOptions = [...enterpriseOptions.value, ...personalOptions.value]
  const option = allOptions.find(opt => opt.id === id)
  return option?.name || id
}

// 消息功能按钮处理函数
async function copyMessage(content: string) {
  try {
    // 移除HTML标签，只复制纯文本
    const textContent = content.replace(/<[^>]*>/g, '')
    await navigator.clipboard.writeText(textContent)
    ElMessage.success('内容已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    // 降级方案：使用传统方法复制
    const textArea = document.createElement('textarea')
    textArea.value = content.replace(/<[^>]*>/g, '')
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('内容已复制到剪贴板')
    } catch (fallbackError) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

function splitScreen(translatedContent: string) {
  // 分屏功能 - 在聊天区域内左右分屏显示
  // 找到对应的原文内容（最近的用户消息）
  const lastUserMessage = messages.value.slice().reverse().find(msg => msg.type === 'user')
  const originalContent = lastUserMessage?.content || '未找到原文内容'

  splitScreenData.value = {
    original: originalContent,
    translated: translatedContent
  }
  isSplitScreen.value = true

  // 滚动到顶部以便更好地查看分屏内容
  nextTick(() => {
    const chatContent = document.querySelector('.chat-content')
    if (chatContent) {
      chatContent.scrollTop = 0
    }
  })
}

// 关闭分屏
function closeSplitScreen() {
  isSplitScreen.value = false
  splitScreenData.value = {
    original: '',
    translated: ''
  }
}



// 复制面板文本
async function copyPanelText(text: string) {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('内容已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('内容已复制到剪贴板')
    } catch (fallbackError) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}

// 下载文本文件
function downloadText(text: string, filename: string) {
  try {
    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    ElMessage.success(`文件 ${filename} 已下载`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 停止生成功能
const stopGeneration = () => {
  if (isTyping.value && currentTypingTimeout.value) {
    clearTimeout(currentTypingTimeout.value)
    isTyping.value = false
    currentTypingTimeout.value = null
    ElMessage.info('已停止生成')
  }
}

async function refreshMessage(message: Message) {
  // 刷新消息 - 重新生成AI回答
  if (message.type !== 'assistant') return

  try {
    // 找到对应的用户消息
    const messageIndex = messages.value.findIndex(msg => msg.time === message.time)
    if (messageIndex > 0) {
      const userMessage = messages.value[messageIndex - 1]
      if (userMessage.type === 'user') {
        // 显示加载状态
        message.content = '正在重新生成回答...'

        // 模拟API调用（这里需要替换为实际的API调用）
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 重新生成回答（这里是模拟，实际应该调用翻译API）
        const refreshedContent = `重新生成的翻译结果：${userMessage.content}`
        message.content = refreshedContent
        message.time = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })

        ElMessage.success('回答已刷新')
      }
    }
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请重试')
    message.content = '刷新失败，请重试'
  }
}

function deleteMessage(message: Message) {
  // 删除消息 - 同时删除对应的用户消息
  try {
    const messageIndex = messages.value.findIndex(msg => msg.time === message.time)
    if (messageIndex > -1) {
      // 如果是AI消息，也删除前面的用户消息
      if (message.type === 'assistant' && messageIndex > 0) {
        const prevMessage = messages.value[messageIndex - 1]
        if (prevMessage.type === 'user') {
          messages.value.splice(messageIndex - 1, 2) // 删除用户消息和AI消息
          ElMessage.success('已删除对话')
        } else {
          messages.value.splice(messageIndex, 1) // 只删除AI消息
          ElMessage.success('已删除消息')
        }
      } else {
        messages.value.splice(messageIndex, 1)
        ElMessage.success('已删除消息')
      }

      // 如果删除后分屏模式还开着，关闭分屏
      if (isSplitScreen.value) {
        closeSplitScreen()
      }
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 添加拖拽和粘贴相关状态
const isDragOver = ref(false)
const inputRef = ref<HTMLInputElement>()

// 处理粘贴事件
function handlePaste(event: ClipboardEvent) {
  const items = event.clipboardData?.items
  if (!items) return
  
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    
    // 处理图片粘贴
    if (item.type.indexOf('image') !== -1) {
      event.preventDefault()
      const file = item.getAsFile()
      if (file) {
        addFileToUpload(file)
        inputMessage.value = inputMessage.value + `[已粘贴图片: ${file.name || 'image.png'}] `
      }
    }
    
    // 处理文本粘贴（可能包含表格数据）
    if (item.type === 'text/plain') {
      item.getAsString((text) => {
        // 检测是否为表格数据（制表符分隔或逗号分隔）
        if (isTableData(text)) {
          createTableFile(text)
        }
      })
    }
    
    // 处理HTML粘贴（从Excel等复制的表格）
    if (item.type === 'text/html') {
      item.getAsString((html) => {
        const tableData = extractTableFromHTML(html)
        if (tableData) {
          createTableFile(tableData)
        }
      })
    }
  }
}

// 处理拖拽进入
function handleDragEnter(event: DragEvent) {
  event.preventDefault()
  isDragOver.value = true
}

// 处理拖拽悬停
function handleDragOver(event: DragEvent) {
  event.preventDefault()
}

// 处理拖拽离开
function handleDragLeave(event: DragEvent) {
  event.preventDefault()
  // 检查是否真的离开了拖拽区域
  const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
  const x = event.clientX
  const y = event.clientY
  
  if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
    isDragOver.value = false
  }
}

// 处理文件拖拽放置
function handleDrop(event: DragEvent) {
  event.preventDefault()
  isDragOver.value = false
  
  const files = event.dataTransfer?.files
  if (files) {
    Array.from(files).forEach(file => {
      addFileToUpload(file)
    })
    
    if (files.length > 0) {
      inputMessage.value = inputMessage.value + `[已拖拽 ${files.length} 个文件] `
    }
  }
}

// 添加文件到上传列表
function addFileToUpload(file: File) {
  const uploadedFile: UploadedFile = {
    id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
    name: file.name,
    size: file.size,
    type: file.type,
    file: file
  }
  uploadedFiles.value.push(uploadedFile)
}

// 检测是否为表格数据
function isTableData(text: string): boolean {
  const lines = text.split('\n').filter(line => line.trim())
  if (lines.length < 2) return false
  
  // 检查是否有制表符或多个逗号分隔
  const hasTabSeparator = lines.some(line => line.includes('\t'))
  const hasCommaSeparator = lines.some(line => (line.match(/,/g) || []).length >= 2)
  
  return hasTabSeparator || hasCommaSeparator
}

// 从HTML中提取表格数据
function extractTableFromHTML(html: string): string | null {
  const parser = new DOMParser()
  const doc = parser.parseFromString(html, 'text/html')
  const table = doc.querySelector('table')
  
  if (!table) return null
  
  const rows = table.querySelectorAll('tr')
  const tableData: string[] = []
  
  rows.forEach(row => {
    const cells = row.querySelectorAll('td, th')
    const rowData = Array.from(cells).map(cell => cell.textContent?.trim() || '')
    tableData.push(rowData.join('\t'))
  })
  
  return tableData.join('\n')
}

// 创建表格文件
function createTableFile(tableData: string) {
  const blob = new Blob([tableData], { type: 'text/plain' })
  const file = new File([blob], `table_${Date.now()}.txt`, { type: 'text/plain' })
  addFileToUpload(file)
  inputMessage.value = inputMessage.value 
}

const textareaRef = ref<HTMLTextAreaElement>()

function adjustTextareaHeight() {
  if (textareaRef.value) {
    // 重置高度以获取正确的scrollHeight
    textareaRef.value.style.height = 'auto'
    
    // 计算新高度，最小40px，最大120px
    const minHeight = 40
    const maxHeight = 120
    const scrollHeight = textareaRef.value.scrollHeight
    
    if (scrollHeight <= maxHeight) {
      textareaRef.value.style.height = Math.max(scrollHeight, minHeight) + 'px'
    } else {
      textareaRef.value.style.height = maxHeight + 'px'
    }
  }
}

// 组件挂载时初始化输入框高度
onMounted(() => {
  nextTick(() => {
    adjustTextareaHeight()
  })
})

// 监听文件列表变化，调整输入框padding
watch(uploadedFiles, () => {
  nextTick(() => {
    adjustTextareaHeight()
  })
}, { deep: true })

// 监听输入内容变化
watch(inputMessage, () => {
  nextTick(() => {
    adjustTextareaHeight()
  })
})
</script>

<style scoped>
.chat-header {
  padding: 1rem 3rem 1.5rem 3rem;
  background: var(--minimal-bg);
  border-bottom: 1px solid rgba(91, 124, 255, 0.08);
}

.section-title {
  display: flex;
  align-items: center;
  margin: 0;
}
.title-bar {
  width: 4px;
  height: 20px;
  background: var(--minimal-primary-gradient);
  border-radius: 2px;
  margin-right: 12px;
}

.chart-query-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-container {
  width: 100%;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
/*   padding: 40px 20px 20px 20px; */
  display: flex;
  flex-direction: column;
}

.chat-welcome {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
  text-align: center;
  padding: 60px 20px;
  min-height: 400px;
}

.welcome-avatar {
  margin-bottom: 30px;
}

.avatar-gif {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 24px;
opacity: 1;
  box-shadow: 0px 0px 20px 0px rgba(164, 133, 255, 0.5);
}

.welcome-text h3 {
  font-size: 24px;
  font-weight: 500;
  color: #323742;
  margin: 0 0 20px 0;
  font-family: Source Han Sans;
}

.welcome-text p {
  letter-spacing: 0px;
  font-variation-settings: "opsz" auto;
  font-feature-settings: "kern" on;
  font-size: 16px;
  color: #323742;
  line-height: 1.6;
  margin: 0 0 10px 0;
  line-height: 26px;
  font-family: Source Han Sans;
}

.sub-text {
  font-size: 14px !important;
  color: #999 !important;
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 12px;
  flex-shrink: 0;
}

.message-avatar .avatar-gif {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.user-avatar {
  background: var(--minimal-primary-gradient);
  color: white;
  font-weight: 600;
  font-size: 14px;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-content {
  max-width: 75%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.message-text {
  padding: 16px 20px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.5;
  word-wrap: break-word;
  margin-bottom: 6px;
}

.message.user .message-text {
  background: var(--minimal-primary-gradient);
  color: white;
  border-bottom-right-radius: 6px;
}

.message.assistant .message-text {
  background: #f1f3f5;
  color: #333;
  border-bottom-left-radius: 6px;
}



.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 6px;
  padding: 0 4px;
  opacity: 0.8;
}

.message.user .message-time {
  text-align: right;
  color: #999;
}

/* 分屏显示样式 - 极简风格 */
.split-screen-container {
  border-radius: 8px;
  margin: 16px 0;

}

/* 分屏顶部区域 */
.split-screen-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
}

.left-avatar {
  display: flex;
  align-items: center;
}

.right-close {
  display: flex;
  align-items: center;
}

.split-screen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.split-screen-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #374151;
}

.close-split-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  background: #f3f4f6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #6b7280;
}

.close-split-btn:hover {
  background: #e5e7eb;
  color: #374151;
  transform: scale(1.05);
}

.split-screen-content {
  gap:10px;
  display: flex;
  height: 400px;
}

.split-panel {
  border: 1px solid #e5e7eb;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.split-divider {
  width: 1px;
  background: #e5e7eb;
  flex-shrink: 0;
}

/* 左侧面板上方的小人动图 */
.panel-top-avatar {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 16px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.top-avatar-gif {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
}

.panel-header {
  padding: 12px 16px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  gap: 8px;
}

.panel-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  overflow: hidden;
}


.panel-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
}

/* 状态图标样式 */
.status-icon {
  margin-right: 8px;
  font-size: 16px;
}

.input-status {
  color: #3b82f6; /* 蓝色表示输入状态 */
}

.complete-status {
  color: #10b981; /* 绿色表示完成状态 */
}

/* 面板操作按钮区域 - 放在每个面板内容下方 */
.panel-actions {
  padding: 0px 16px !important;
  background: #f9fafb !important;
  border-top: 1px solid #e5e7eb !important;
  display: flex !important;
  gap: 8px !important;
  justify-content: flex-start !important;
  border-radius: 0 0 12px 12px;
  min-height: 48px;
  align-items: center;
}

.panel-action-btn {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  width: 32px !important;
  height: 32px !important;
/*   border: 1px solid #d1d5db !important;
  background: #ffffff !important; */
  border-radius: 6px !important;
  cursor: pointer !important;
  transition: all 0.2s ease !important;
  color: #6b7280 !important;
  opacity: 1 !important;
  visibility: visible !important;
}

.panel-action-btn:hover {
  background: #f3f4f6 !important;
  border-color: #9ca3af !important;
  color: #374151 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
}

.panel-action-btn .el-icon {
  font-size: 16px !important;
}



.panel-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #ffffff;
}

.panel-content::-webkit-scrollbar {
  width: 4px;
}

.panel-content::-webkit-scrollbar-track {
  background: transparent;
}

.panel-content::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 2px;
}

.panel-content::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

.panel-text {
  font-size: 14px;
  line-height: 1.6;
  color: #374151;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* Markdown 内容样式 */
.markdown-content {
  white-space: normal !important;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #1f2937;
}

.markdown-content h1 { font-size: 24px; }
.markdown-content h2 { font-size: 20px; }
.markdown-content h3 { font-size: 18px; }
.markdown-content h4 { font-size: 16px; }
.markdown-content h5 { font-size: 14px; }
.markdown-content h6 { font-size: 12px; }

.markdown-content p {
  margin: 8px 0;
  line-height: 1.6;
}

.markdown-content ul,
.markdown-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content blockquote {
  margin: 12px 0;
  padding: 8px 16px;
  background: #f8f9fa;
  border-left: 4px solid #6b7280;
  border-radius: 4px;
}

.markdown-content code {
  background: #f1f5f9;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  color: #dc2626;
}

.markdown-content pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
  border: 1px solid #e5e7eb;
}

.markdown-content pre code {
  background: transparent;
  padding: 0;
  color: #374151;
  font-size: 13px;
  line-height: 1.5;
}

.markdown-content table {
  width: 100%;
  border-collapse: collapse;
  margin: 12px 0;
  font-size: 13px;
}

.markdown-content th,
.markdown-content td {
  border: 1px solid #e5e7eb;
  padding: 8px 12px;
  text-align: left;
}

.markdown-content th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
}

.markdown-content a {
  color: #3b82f6;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

.markdown-content strong {
  font-weight: 600;
  color: #1f2937;
}

.markdown-content em {
  font-style: italic;
}

.markdown-content hr {
  margin: 16px 0;
  border: none;
  border-top: 1px solid #e5e7eb;
}

/* 用户头像样式 */
.original-panel .panel-avatar {
  background: #3b82f6;
  color: #ffffff;
  font-size: 12px;
  font-weight: 500;
}

/* AI头像样式 */
.translated-panel .panel-avatar {
  background: #10b981;
  color: #ffffff;
}



/* 消息功能按钮样式 */
.message-actions {
  display: flex;
  gap: 6px;
  margin-top: 10px;
  opacity: 1;
  transition: opacity 0.3s ease;
  justify-content: flex-start;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border: none;
  background: rgba(248, 249, 250, 0.9);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 0;
  border: 1px solid rgba(0, 0, 0, 0.04);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
}

.action-btn:hover {
  background: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: rgba(91, 124, 255, 0.2);
}

.action-btn img {
  width: 14px;
  height: 14px;
  opacity: 0.7;
  transition: opacity 0.2s ease;
}

.action-btn:hover img {
  opacity: 1;
}

/* 特定按钮的悬停颜色 */
.action-btn:nth-child(1):hover {
  background: rgba(34, 197, 94, 0.05);
}

.action-btn:nth-child(2):hover {
  background: rgba(59, 130, 246, 0.05);
}

.action-btn:nth-child(3):hover {
  background: rgba(245, 158, 11, 0.05);
}

.action-btn:nth-child(4):hover {
  background: rgba(239, 68, 68, 0.05);
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  30% {
    transform: translateY(-6px);
    opacity: 1;
  }
}

.chat-input {
width: 100%;
  padding: 0px 0px;
  margin: auto;
}

.input-container {
  position: relative;
}

.input-wrapper {
  display: flex;
  align-items: stretch;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  padding: 0;
  transition: all 0.2s ease;
  min-height: 64px;
  font-size: 16px;
  position: relative;
  flex-direction: column;
}

.input-wrapper:hover {
  border-color: #40a9ff;
}

.input-wrapper:focus-within {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.input-wrapper.drag-over {
  background: rgba(24, 144, 255, 0.05);
  border-color: #1890ff;
  border-style: dashed;
}


:deep(.el-select--small .el-select__wrapper){
  width:100%;
  border-radius: 18px;
}

/* 文本输入容器 */
.textarea-container {
  flex: 1;
  display: flex;
}

.message-input {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  font-size: 14px;
  padding: 16px;
  color: #333;
  line-height: 1.5;
  resize: none;
  min-height: 40px;
  max-height: 120px;
  overflow-y: auto;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  box-sizing: border-box;
}

/* 底部功能区 */
.input-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
}

.input-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-input::placeholder {
  color: #bfbfbf;
}



.input-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f5f5f5;
  color: #666;
}

.action-btn:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.upload-btn {
  background: transparent;
  color: #999;
}

.upload-btn:hover {
  background: #f0f0f0;
  color: #666;
}

.file-size-selector {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #666;
}

.size-text {
  white-space: nowrap;
}

.size-select {
  border: none;
  background: transparent;
  color: #666;
  font-size: 12px;
  cursor: pointer;
  outline: none;
  padding: 2px 4px;
}

.size-select:hover {
  background: #f0f0f0;
  border-radius: 4px;
}

.send-btn {
  background:var(--minimal-primary-gradient);
  color: white;
  border-radius: 6px;
  margin-left: auto;
}

.send-btn:hover:not(:disabled) {
  background:var(--minimal-primary-gradient);
}

.send-btn:disabled {
  background: #f5f5f5;
  color: #bfbfbf;
  cursor: not-allowed;
}

.upload-btn {
  background: #f9fafb;
  color: #6b7280;
  border: 1px solid #d1d5db;
  transition: all 0.2s ease;
}

.upload-btn:hover {
  background: #f3f4f6;
  color: #374151;
  border-color: #9ca3af;
}

/* 文件标签页样式 - 显示在输入区域外部上方 */
.uploaded-files-outside {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
  padding: 12px;
  border-radius: 8px;
}

.file-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #ffffff;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 12px;
  max-width: 200px;
  transition: all 0.2s ease;
}

.file-tab:hover {
  border-color: #9ca3af;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.file-tab-icon {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.file-tab-content {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.file-tab-title {
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

.file-tab-url {
  color: #6b7280;
  font-size: 11px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
  margin-top: 2px;
}


.file-tab-close {
  flex-shrink: 0;
  background: none;
  border: none;
  color: #9ca3af;
  cursor: pointer;
  padding: 2px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.file-tab-close:hover {
  background: #f3f4f6;
  color: #ef4444;
}



.input-footer {
  margin-top: 12px;
  text-align: center;
}

.footer-text {
  font-size: 12px;
  color: #999;
}

.message-files {
  margin-top: 8px;
}

.message-file {
  display: flex;
  align-items: center;
  background: #fafafa;
  border-radius: 4px;
  padding: 6px 10px;
  font-size: 12px;
  color: #666;
  gap: 6px;
  margin-bottom: 4px;
}

.message.user .message-file {
  background: rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 0.9);
}

.input-advanced {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-top: 8px;
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}
.web-search-switch {
  display: flex;
  align-items: center;
  gap: 6px;
  user-select: none;
}
.model-select {
  display: flex;
  align-items: center;
  gap: 6px;
}
.model-select select {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
  outline: none;
  transition: border 0.2s;
}
.model-select select:focus {
  border-color: #1890ff;
}
/* 框内左下角功能区 */
.input-advanced-inside {
  position: absolute;
  left: 16px;
  bottom: 10px;
  display: flex;
  align-items: center;
  gap: 18px;
  font-size: 13px;
  color: #888;
  z-index: 2;
  background: transparent;
  pointer-events: auto;
}
.input-advanced-inside .language-select {
  min-width: 120px;
  font-size: 13px;
  border-radius: 4px;
}

.input-advanced-inside .language-select .el-select__wrapper {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  transition: all 0.3s ease;
  background: white;
}

.input-advanced-inside .language-select .el-select__wrapper:hover {
  border-color: #5b7cff;
}
/* 移除下方这段会覆盖主色的规则 */
/* :deep(.input-advanced-inside .el-button.is-primary) {
  background: #1890ff;
  color: #fff;
  border-color: #1890ff;
  box-shadow: none;
} */
:deep(.input-advanced-inside .el-button.is-primary:focus),
:deep(.input-advanced-inside .el-button.is-primary:active) {
  border-color: #1890ff !important;
  box-shadow: none !important;
}
.input-advanced-inside .model-select {
  min-width: 100px;
}
.model-select-popper {
  font-size: 13px;
}
.input-advanced-inside .switch-label {
  margin-left: 2px;
}
.input-advanced-inside .model-select {
  display: flex;
  align-items: center;
  gap: 4px;
}
.input-advanced-inside select {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 13px;
  outline: none;
  background: #fafbfc;
  color: #333;
  transition: border 0.2s;
}
.input-advanced-inside select:focus {
  border-color: #1890ff;
}
@media (max-width: 600px) {
  .input-advanced-inside {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
    left: 8px;
    bottom: 8px;
  }
}
</style>

<!-- 新增全局样式，确保渐变主色全局覆盖 -->
<style>
/* 最高优先级的样式覆盖 */
:deep(.el-button--primary) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus),
:deep(.el-button--primary:active) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

/* 专门针对联网搜索按钮 */
.web-search-btn.el-button--primary {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

.web-search-btn.el-button--primary:hover,
.web-search-btn.el-button--primary:focus,
.web-search-btn.el-button--primary:active {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

/* 输入框内的按钮 */
:deep(.input-advanced-inside .el-button--primary) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.input-advanced-inside .el-button--primary:hover),
:deep(.input-advanced-inside .el-button--primary:focus),
:deep(.input-advanced-inside .el-button--primary:active) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  background-image: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

.ai-status {
  display: flex;
  align-items: center;
  gap: 6px;
  background: rgba(91, 124, 255, 0.08);
  color: #5b7cff;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  margin-bottom: 12px;
  width: fit-content;
  border: 1px solid rgba(91, 124, 255, 0.15);
}

.status-icon {
  font-size: 10px;
  font-weight: bold;
}

.status-text {
  font-weight: 500;
}

/* 翻译加载动画样式 */
.translation-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 40px 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 600px;
  width: 100%;
}

.loading-avatar {
  margin-bottom: 24px;
}

.loading-avatar .avatar-gif {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 3px solid #f0f0f0;
}

.loading-content {
  width: 100%;
  text-align: center;
}

.loading-header {
  margin-bottom: 32px;
}

.loading-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin-bottom: 16px;
}

.loading-icon {
  font-size: 24px;
  animation: rotate 2s linear infinite;
}

.loading-title h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.loading-progress {
  display: flex;
  align-items: center;
  gap: 12px;
  justify-content: center;
}

.progress-bar {
  flex: 1;
  max-width: 300px;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  min-width: 40px;
}

.loading-steps {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  opacity: 0.4;
  transition: all 0.3s ease;
}

.step.active {
  opacity: 1;
}

.step.completed {
  opacity: 1;
}

.step-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  color: #999;
  transition: all 0.3s ease;
}

.step.active .step-icon {
  background: #667eea;
  color: white;
}

.step.completed .step-icon {
  background: #52c41a;
  color: white;
}

.step-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #fff;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.step-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.step.active .step-text {
  color: #667eea;
}

.step.completed .step-text {
  color: #52c41a;
}

.loading-tips {
  margin-top: 16px;
}

.tip-text {
  font-size: 14px;
  color: #888;
  margin: 0;
  animation: fadeInOut 2s ease-in-out infinite;
}

/* 动画定义 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .loading-steps {
    gap: 16px;
  }

  .step-icon {
    width: 28px;
    height: 28px;
    font-size: 12px;
  }

  .loading-title h3 {
    font-size: 18px;
  }

  .progress-bar {
    max-width: 200px;
  }
}

/* 发送按钮图标大小调整 */
.send-btn .el-icon {
  font-size: 20px !important;
}

.upload-btn .el-icon {
  font-size: 20px !important;
}

/* 确保按钮内图标居中 */
.send-btn, .upload-btn {
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}
</style>





